package com.tjsinfo.tjsoa.mail.action;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.json.JSONObject;

import com.tjsinfo.tjsoa.Dao.IJDBCDao;
import com.tjsinfo.tjsoa.common.DealString;
import com.tjsinfo.tjsoa.common.FileManage;
import com.tjsinfo.tjsoa.common.SessionUser;
import com.tjsinfo.tjsoa.common.ToolKit;
import com.tjsinfo.tjsoa.mail.bo.ITjsemailReceivedBo;
import com.tjsinfo.tjsoa.mail.bo.ITjsmailBo;
import com.tjsinfo.tjsoa.mail.bo.TjsDraftBo;
import com.tjsinfo.tjsoa.mail.dao.TjsDrefAnnexDao;
import com.tjsinfo.tjsoa.mail.vo.TjsAnnex;
import com.tjsinfo.tjsoa.mail.vo.Tjsmail;
import com.tjsinfo.tjsoa.message.bo.ITjsMessageBo;
import com.tjsinfo.tjsoa.message.vo.TjsMessage;
import com.tjsinfo.tjsoa.system.vo.Files;
import com.tjsinfo.tjsoa.system.vo.TSystemUser;
import com.tjsinfo.tjsoa.system.vo.User;


/**
 * 写信action
 * @author wangxiaowei
 *
 */
public class WriteMail2Action extends Action{
	private  ITjsmailBo tjsmailBo;
	private  ITjsemailReceivedBo tjsemailReceivedBo;
	private IJDBCDao jdbcdao;
	private TjsDraftBo tjsDraftBo;
	private TjsDrefAnnexDao tjsDrefAnnexDao;
	public void setTjsDraftBo(TjsDraftBo tjsDraftBo) {
		this.tjsDraftBo = tjsDraftBo;
	}
	public void setTjsDrefAnnexDao(TjsDrefAnnexDao tjsDrefAnnexDao) {
		this.tjsDrefAnnexDao = tjsDrefAnnexDao;
	}
	public void setJdbcdao(IJDBCDao jdbcdao) {
		this.jdbcdao = jdbcdao;
	}
	public void setTjsmailBo(ITjsmailBo tjsmailBo) {
		this.tjsmailBo = tjsmailBo;
	}
	public void setTjsemailReceivedBo(ITjsemailReceivedBo tjsemailReceivedBo) {
		this.tjsemailReceivedBo = tjsemailReceivedBo;
	}
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			{
		
		// TODO Auto-generated method stub
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			
			MessageResources message=getResources(request);
			//提交上传附件
			String fromFilePath=message.getMessage(request.getLocale(), "system.uploadFile.tempFilePath");
			String nowSQL = ToolKit.getProperties("com/tjsinfo/tjsoa/mail/properties/systemResource.properties", this).getProperty("nowSQL");
			String toFilePath = ToolKit.getProperties("com/tjsinfo/tjsoa/mail/properties/systemResource.properties", this).getProperty(nowSQL+".fileurl");
			List<Files> fileList=DealString.fileCopyTofile(request, fromFilePath, toFilePath);
			List<TjsAnnex> list = new ArrayList<TjsAnnex>();
			for (Files files : fileList) {
				TjsAnnex tjsAnnex = new TjsAnnex();
				tjsAnnex.setAnnexName(files.getNewFileName());
				tjsAnnex.setAnnexZhenName(files.getOldFileName());
				tjsAnnex.setAnnexAddress("");
				File   f   =   new   File(toFilePath+files.getNewFileName()); 
				int size = ((int)(100*f.length())/1024);
				tjsAnnex.setAnnexSize(size);
				list.add(tjsAnnex);
			}						
			
			String zhusong = request.getParameter("sendid");
			//zhusong = "1,系统管理员,RQSOA@177,王莹,RQSOAA@171,王宝,RQSOAB";
			//zhusong = "177,王莹,RQSOAA@";
			//List chaxunName = new ArrayList(); 
			//String sendInput = request.getParameter("sendInput");//姓名连数据库集合
			
			Tjsmail tjsmail=new Tjsmail();
			//String chaosong = request.getParameter("chaosongid");
			//String misong = request.getParameter("misongid");
			String uuuuuuu = request.getParameter("uuuuuuu");
			String contest = request.getParameter("contest");
			String title = request.getParameter("title");
			String sendusers = request.getParameter("sendusers");
			String sendInput = "";
			String sql = "select rec_userid from t_mail_tjsemailreceived where rec_username='"+uuuuuuu+"'";
			ResultSet rs = jdbcdao.executeQuary(sql);
			try {
				while(rs.next()){
					sendInput= rs.getString("rec_userid");
					}
			} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			TSystemUser tjsUser=new TSystemUser();
			//tjsmail.setTjsUser(tjsUser);	
			
			//String mailid =	tjsmailBo.addSendMail(title, value, new Date(), 1, SessionUser.getUserId(request), 1,list, SessionUser.getUser(request).getUsername(),nowSQL);
			String mailid =	tjsmailBo.addSendMail(title, contest, new Date(), 1, SessionUser.getUserId(request), 1,list,SessionUser.getUser(request).getUsername(),nowSQL);
			tjsemailReceivedBo.addTjsmailReceived(mailid, sendInput, 1, 1,uuuuuuu);
			

			HashMap<String, List<String>> sqlMap = new HashMap<String, List<String>>();
			List<String> nowList = new ArrayList<String>();//发送当前数据库的用户

			HashMap<String, String> otherMap = new HashMap<String, String>();//发送其他数据库的用户

			String other = "";//发送其他数据库的用户，用户名逗号分隔
			List<String> list1 = new ArrayList<String>();
			
			
			//当前系统人员录入
			/*for (Iterator iterator = nowList.iterator(); iterator.hasNext();) {
				String str = (String) iterator.next();
				String userid = str.split(",")[0];
				String username = str.split(",")[1];
				tjsemailReceivedBo.addTjsmailReceived(mailid,userid, 1, 1,username);
				
			}
			//当前系统人员录入其他系统的接收人
			String[] s = other.split(",");
			for (int i = 1; i < s.length; i++) {
				HttpSession session = request.getSession();
				User user = (User) session.getAttribute("user");
				String uuuuuuu = request.getParameter("uuuuuuu");
				String sendusers = request.getParameter("sendusers");
				//int userid = Integer.valueOf(sendusers).intValue();
				//tjsmail.setTjsmailUserid(Integer.valueOf(sendusers).intValue());
				tjsemailReceivedBo.addTjsmailReceived(mailid, sendusers, 1, 1,uuuuuuu);
				/*String uuid = UUID.randomUUID().toString().replace("-", "");
				String uuidMail = UUID.randomUUID().toString().replace("-", "");
				String sql = "insert into dbo.t_mail_tjsemailReceived(rec_id,rec_email,rec_start,rec_userid,rec_nature,rec_type,rec_tag,rec_username)" +
				" values('"+uuid+"','"+uuidMail+"',1,'"+sendusers+"',1,1,0,'"+uuuuuuu+"');";
				jdbcdao.executeUpdate(sql);
			}
		*/
			
			//其他系统接收人，循环有几个数据库
			Iterator iter = sqlMap.entrySet().iterator(); 
			while (iter.hasNext()) {
			    Map.Entry entry = (Map.Entry) iter.next(); 
			    String mssqlNum= (String) entry.getKey();//单个的其他数据库
			    String mssql = ToolKit.getProperties("com/tjsinfo/tjsoa/mail/properties/systemResource.properties", this).getProperty(mssqlNum);
			    List<String> val = (List<String>) entry.getValue();//其他数据库中的接收人 
			    
			    /**
			     * 开始，向数据库插入email主表发送信息，附件信息
			     */
				String uuidMail = UUID.randomUUID().toString().replace("-", "");
				String sql2 = "insert into "+mssql+".dbo.t_mail_tjsmail(tjsmail_id,tjsmail_title,tjsmail_value,tjsmail_datatime,tjsmail_type,tjsmail_userid,tjsmail_start,tismail_read,tismail_tag,tjsmail_username,send_sql)" +
						" values('"+uuidMail+"','"+title+"','"+contest+"','"+sdf.format(new Date())+"',1,"+SessionUser.getUserId(request)+",1,1,0,'"+SessionUser.getUser(request).getUsername()+"','"+nowSQL+"');";
				jdbcdao.executeUpdate(sql2);
				
				//mail数据表插入附件数据

				String toPath = ToolKit.getProperties("com/tjsinfo/tjsoa/mail/properties/systemResource.properties", this).getProperty(mssqlNum+".fileurl");
				for (Iterator iterator = list.iterator(); iterator.hasNext();) {
					TjsAnnex tjsAnnex = (TjsAnnex) iterator.next();
					if(tjsAnnex.getAnnexName() !=null)
					{
						String fuuid = UUID.randomUUID().toString().replace("-", "");
						sql = "insert into "+mssql+".dbo.t_mail_tjsAnnex(annex_id,annex_zhenname,annex_name,annex_address,email_id,annex_size)" +
								" values('"+fuuid+"','"+tjsAnnex.getAnnexZhenName()+"','"+tjsAnnex.getAnnexName()+"','','"+uuidMail+"',"+tjsAnnex.getAnnexSize()+");";
						jdbcdao.executeUpdate(sql);
					}
					FileManage.moveFile(toFilePath+tjsAnnex.getAnnexName(), toPath+tjsAnnex.getAnnexName());
				}
				/**
			     * 结束
			     *//*
				
				*//**
			     * 开始，向发送的其他数据库，插入循环到当前系统数据库的接收人员信息

			     */
				/*
				for (Iterator iterator = nowList.iterator(); iterator.hasNext();) {
					String str = (String) iterator.next();
					String sendusers = request.getParameter("uuuuuuu");
					String username = str.split(",")[1];
					String uuid = UUID.randomUUID().toString().replace("-", "");
					String sql1 = "insert into "+mssql+".dbo.t_mail_tjsemailReceived(rec_id,rec_email,rec_start,rec_userid,rec_nature,rec_type,rec_tag,rec_username)" +
					" values('"+uuid+"','"+uuidMail+"',1,null,1,1,0,'"+sendusers+"');";
					jdbcdao.executeUpdate(sql1);
				}
				*/
				/*
			     * 开始，向发送的其他数据库，插入其他数据库的接收人员信息
			     */
				/*
				Iterator iter1 = otherMap.entrySet().iterator(); 
				while (iter1.hasNext()) {
				    Map.Entry entry1 = (Map.Entry) iter1.next(); 
				    String username = (String) entry1.getKey();
				    String sendusers = request.getParameter("uuuuuuu");
				    String userid = (String) entry1.getValue();
				    boolean bl = true;
				    for (Iterator iterator = val.iterator(); iterator.hasNext();) {
						String str = (String) iterator.next();
						if (username.equals(str.split(",")[1])) {//当前循环到的其他数据库系统用户

							String uuid = UUID.randomUUID().toString().replace("-", "");
							String sql1 = "insert into "+mssql+".dbo.t_mail_tjsemailReceived(rec_id,rec_email,rec_start,rec_userid,rec_nature,rec_type,rec_tag,rec_username)" +
							" values('"+uuid+"','"+uuidMail+"',1,"+userid+",1,1,0,'"+sendusers+"');";
							jdbcdao.executeUpdate(sql1);
							
							bl = false;
							continue;
						}
					}
				    if (bl) {//其他数据库的系统用户
				    	String uuid = UUID.randomUUID().toString().replace("-", "");
						String sql1 = "insert into "+mssql+".dbo.t_mail_tjsemailReceived(rec_id,rec_email,rec_start,rec_userid,rec_nature,rec_type,rec_tag,rec_username)" +
						" values('"+uuid+"','"+uuidMail+"',1,null,1,1,0,'"+sendusers+"');";
						jdbcdao.executeUpdate(sql1);
					}
				}
				*/
			} 
			jdbcdao.closeStmt();
			Connection con = jdbcdao.getConn();
			try {
				if (!con.isClosed()) {
					jdbcdao.closeConn();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			request.setAttribute("linkurl", "tjsinfo/tjsoa/mail/selectEmaiList.do");
			request.setAttribute("message", "email.message.sendemail");
			request.setAttribute("count", tjsemailReceivedBo.count(String.valueOf(SessionUser.getUserId(request)),1));
			return mapping.findForward("success");
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return mapping.findForward("error");
		}
		
	}
	
}
